import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_table/flutter_html_table.dart';
import 'package:get/get.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/items/avator_label.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/tip_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../controller/pick/subs_article_logic.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/picture_preview_widget.dart';

class SubsArticlePage extends StatefulWidget {
  const SubsArticlePage({Key? key}) : super(key: key);

  @override
  State<SubsArticlePage> createState() => _SubsArticlePageState();
}

class _SubsArticlePageState extends State<SubsArticlePage> {
  final SubsArticleLogic logic = Get.put(SubsArticleLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: Styles.appBar(leadingColor: Colours.text292D32),
        body: GetBuilder<SubsArticleLogic>(builder: (logic) {
          return VisibilityDetector(
            key: Key("article"),
            onVisibilityChanged: (VisibilityInfo info) {
              if (!info.visibleBounds.isEmpty) {
                logic.getData();
              }
            },
            child: LoadingWidget<bool>(
              isLoading: logic.data == null,
              data: logic.data?.id == null,
              child: () => Stack(
                children: [
                  SizedBox(
                    height: Get.height,
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          QkdText(logic.data?.title ?? "",
                            fontSize: 22,
                            color: Colours.text292D32,
                            fontWeight: FontWeight.w500
                          ).paddingSymmetric(horizontal: 16),
                          Container(height: 8),
                          QkdText(logic.info.join(),
                            fontSize: 12, color: Colours.grey99
                          ).paddingSymmetric(horizontal: 16),
                          Container(height: 16),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: AvatarLabel.record(
                                  avatarUrl: logic.data?.logo,
                                  id: logic.data?.expertId,
                                  name: logic.data?.name,
                                  firstTag: logic.data?.firstTag,
                                  secondTag: logic.data?.secondTag,
                                ),
                              ),
                              FocusButton(logic.data?.isFocus ?? 0,
                                  expertId: logic.data?.expertId, onTap: (focus) {
                                if (focus != logic.data?.isFocus) {
                                  logic.getData();
                                }
                              })
                            ],
                          ).paddingSymmetric(horizontal: 16),
                          Container(height: 16),
                          Html(
                            data: getData((logic.data?.summary ?? "") +
                                (logic.data?.read == true
                                    ? (logic.data?.content ?? "")
                                    : "")),
                            extensions: [
                              const TableHtmlExtension(),
                              TagExtension(
                                  tagsToExtend: {"img"},
                                  builder: (extensionContext) {
                                    final e = extensionContext.styledElement;
                                    return GestureDetector(
                                      onTap: () => Get.dialog(PicturePreview(imageUrl: e?.attributes['src'] ?? ""),
                                          useSafeArea: false),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(8),
                                        child: CachedNetworkImage(
                                          imageUrl: e?.attributes['src'] ?? "",
                                          width: Get.width,
                                          fit: BoxFit.cover,
                                          placeholder: (context,url) => Container(),
                                          errorWidget: (context,url,error) => Container(),
                                        ),
                                      ),
                                    );
                                  }
                              ),
                            ],
                            style: {
                              "body": Style(letterSpacing: -0.5),
                              "p": Style(
                                  // backgroundColor: Colors.blue,
                                  margin: Margins.all(0)),
                              "img": Style(
                                  width: Width(Get.width - 40),
                                  height: Height.auto(),
                                  display: Display.block,
                                  textAlign: TextAlign.center),
                              "#wholeBody": Style(
                                  margin: Margins.only(
                                      left: 20, right: 20, top: 8, bottom: 24)),
                              "#article": Style(
                                  color: Colours.text,
                                  // backgroundColor: Colours.redE0402D,
                                  fontSize: FontSize(18),
                                  letterSpacing: -0.6,
                                  lineHeight: const LineHeight(1.6),
                                  whiteSpace: WhiteSpace.normal,
                                  textAlign: TextAlign.justify)
                            },
                          ),
                          if (logic.data?.read != true) ...[
                            Row(
                              children: [
                                Expanded(
                                  child: Container(
                                    height: 0.5, color: Colours.goldBF8361
                                  )
                                ),
                                QkdText(" 以下文字为付费内容 ",
                                  fontSize: 12, color: Colours.goldBF8361
                                ),
                                Expanded(
                                  child: Container(
                                    height: 0.5, color: Colours.goldBF8361
                                  )
                                )
                              ],
                            ).paddingSymmetric(horizontal: 16),
                            Container(height: 14),
                            Stack(
                              children: [
                                Image.asset(
                                    width: Get.width,
                                    Utils.getImgPath("subs_article_back.png")
                                ),
                                Positioned.fill(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Image.asset(
                                        width: 24,
                                        Utils.getImgPath("subs_unreadable.png")
                                      ),
                                      Container(height: 3),
                                      QkdText(logic.data?.tipContent ?? "付费可查看比赛分析",
                                        fontSize: 12,
                                        color: Colours.goldBF8361
                                      )
                                    ],
                                  )
                                )
                              ],
                            ).paddingSymmetric(horizontal: 16),
                            Container(height: 13),
                          ],
                          if (logic.tip != null) ...[
                            QkdText("友情提示",
                              fontSize: 12,
                              color: Colours.grey66,
                              fontWeight: FontWeight.w500
                            ).paddingSymmetric(horizontal: 16),
                            Container(height: 6),
                            const TipWidget(
                              type: "subs_article"
                            ).paddingSymmetric(horizontal: 16),
                          ],
                          Container(height: 80)
                        ],
                      ),
                    ),
                  ),
                  if (logic.data?.read == false)
                    Positioned(bottom: 0, child: _payBar())
                ],
              ),
            ),
          );
        }));
  }

  String getData(String? content) {
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    var regCom = RegExp(r'<\/p>[.\n\s]*<p>');
    var regP = RegExp(r'\/>[.\n\s]*<p>');
    var regImg = RegExp(r'\/>[.\n\s]*<img');
    var regInLine = RegExp(r'<p[^<>]*>[^<>]+<img');
    var regBody = RegExp(r'\/p>[.\n\s]*</body');
    String append = '';
    String? com = content?.splitMapJoin(regInLine, onMatch: (match) {
      var result = match[0]?.split("<img").join("</p><p><img") ?? "";
      return result;
    });
    com = com
            ?.split("<p>&nbsp;</p>")
            .join("<div style= 'height: 25;width: 200px;'>  </div>")
            .split(regCom)
            .join("</p><div style= 'height: 25;width: 200px;'>  </div><p>")
            .split(regP)
            .join("/><div style= 'height: 25;width: 200px;'>  </div><p>")
            .split(regImg)
            .join("/><div style= 'height: 25;width: 200px;'>  </div><img")
            .split(regBody)
            .join("/p><div style= 'height: 25;width: 200px;'>  </div></body") ??
        "";
    log(com);
    com.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });
    var newData = "";
    newData = "<body id='wholeBody'>"
        "<div id='article'>$append</div>"
        "</body>";
    return newData;
  }

  Widget _payBar() {
    return SizedBox(
      width: Get.width,
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              border: Border(top: BorderSide(color: Colours.greyEE,width: 0.5))
            ),
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Row(
              children: [
                if (logic.data?.subsPrice != null &&
                    logic.data?.subsDayTime != null &&
                    logic.data?.subsPrice != "0球币")
                  QkdText("${logic.data?.subsPrice}球币/${logic.data?.subsDayTime}".changeUnit,
                    fontSize: 16,
                    color: Colours.brown6A3313,
                    fontWeight: FontWeight.w500
                  ),
                if (logic.data?.subsPrice == "0球币")
                  QkdText("限时免费",
                    fontSize: 16,
                    color: Colours.brown6A3313,
                    fontWeight: FontWeight.w500
                  ),
                const Spacer(),
                QkdButton(
                    width: 108,
                    height: 40,
                    onPressed: () {
                      Get.toNamed(Routes.subsPay,
                        arguments: logic.data?.expertId);
                    },
                    borderRadius: 20,
                    backgroundColor: Colours.goldF8D486,
                    foregroundColor: Colours.brown6A3313,
                    text: "订阅TA")
              ],
            ),
          ),
          Container(color: Colors.white, height: 20)
        ],
      ),
    );
  }
}
